import { Inject } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable} from "@angular/core";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { Song, SongUrl } from "./data-types/common.types";
import { API_CONFIG, ServicesModule } from "./services.module";

 
//  歌单服务
@Injectable({
  providedIn: ServicesModule
})
export class SongService {
   

  constructor(private http:HttpClient,@Inject(API_CONFIG) private uri:string) { }
  // 请求所有歌曲对应url
  getSongUrl(ids:string):Observable<SongUrl[]>{
    // 
    const params  = new HttpParams().set('id',ids)
    return this.http.get(this.uri+'song/url',{params})
    .pipe(map((res:any)=>res.data))
  }

  // 获取歌曲列表
  getSongList(songs:Song | Song[]):Observable<any>{
    // 转换为数组，拷贝避免引用问题
    const songsArr = Array.isArray(songs)?songs.slice():[songs]
    // 把每个歌曲的id拼接字符串
    const ids =  songsArr.map(item => item.id).join(',')
       return this.getSongUrl(ids).pipe(map(urls => this.generateSongList(songsArr,urls)))
    }
    
    
  // // 获取歌曲列表
  // getSongList(songs:Song | Song[]):Observable<any>{
  //   // 转换为数组，拷贝避免引用问题
  //   const songsArr = Array.isArray(songs)?songs.slice():[songs]
  //   // 把每个歌曲的id拼接字符串
  //   const ids =  songsArr.map(item => item.id).join(',')
  //   return new Observable(observer=>{
  //     // 把获取的歌曲url拼接为song类型
  //     this.getSongUrl(ids).subscribe(urls => {
  //      observer.next( this.generateSongList(songsArr,urls)) 
  //   })
    
  //   })
  // }
  // 5.生成完整歌曲数据类型
  generateSongList(songs:Song[],urls:SongUrl[]):Song[]{
    let result:any = [];
      songs.forEach((song:any )=>{
        const url = urls.find(url => url.id === song.id)?.url
        if(url){
      // 6.组合数据
          result.push({...song , url})
        }
      })
    return result;
  }
}
